import { useState, useCallback, useEffect } from 'react';
import type { Card, Connection, ConnectionSide, Handler } from '../types';
import { deleteConnection as delConn, deleteConnections as delconns, createConnection } from '../api';


export const getCardPosition = (card: Card, side: ConnectionSide) => {
   // 计算起点位置
   switch (side) {
      case 'top':
         return [card.x + card.width / 2, card.y];
      case 'right':
         return [card.x + card.width, card.y + card.height / 2];
      case 'bottom':
         return [card.x + card.width / 2, card.y + card.height];
      case 'left':
         return [card.x, card.y + card.height / 2];
      default:
         return [card.x + card.width / 2, card.y + card.height / 2];
   }
};

// 计算连接线位置
export const getConnectionPosition = (fromCard: Card, toCard: Card, fromSide: ConnectionSide, toSide: ConnectionSide) => {
   let [fromX, fromY] = getCardPosition(fromCard, fromSide);
   let [toX, toY] = getCardPosition(toCard, toSide);
   return { fromX, fromY, toX, toY };
};

// 计算箭头方向
export const getArrowPoints = (fromX: number, fromY: number, toX: number, toY: number) => {
   const angle = Math.atan2(toY - fromY, toX - fromX);
   const headSize = 10;

   return [
      toX,
      toY,
      toX - headSize * Math.cos(angle - Math.PI / 6),
      toY - headSize * Math.sin(angle - Math.PI / 6),
      toX - headSize * Math.cos(angle + Math.PI / 6),
      toY - headSize * Math.sin(angle + Math.PI / 6),
   ];
};

const HandlerCommonStyle: React.CSSProperties = {
   position: 'absolute',
   width: 16,
   height: 16,
   borderRadius: '50%',
   cursor: 'pointer',
   alignItems: 'center',
   justifyContent: 'center',
   fontSize: 10,
   color: '#fff',
   zIndex: 10,
};
const HandlerList: Handler[] = [
   {
      position: 'top',
      style: {
         top: -12,
         left: '50%',
         transform: 'translateX(-50%)',
      },
   },
   {
      position: 'right',
      style: {
         right: -12,
         top: '50%',
         transform: 'translateY(-50%)',
      },
   },
   {
      position: 'bottom',
      style: {
         bottom: -12,
         left: '50%',
         transform: 'translateX(-50%)',
      },
   },
   {
      position: 'left',
      style: {
         left: -12,
         top: '50%',
         transform: 'translateY(-50%)',
      },
   },
];

const useConnections = ({ refresh, tabId }: { refresh: () => void, tabId: string }) => {


   const [connections, setConnections] = useState<Connection[]>([]);
   const [connectingStart, setConnectingStart] = useState<string | null>(null);
   const [connectingSide, setConnectingSide] = useState<ConnectionSide | null>(null);

   // 开始连接
   const startConnection = (cardId: string, side: ConnectionSide) => {
      setConnectingStart(cardId);
      setConnectingSide(side);
   };

   useEffect(() => {
      const handleClickOutside = (event: MouseEvent) => {
         if (connectingStart && event.target && event.target instanceof Element && !event.target.classList.contains('connection-handle')) {
            setConnectingStart(null);
            setConnectingSide(null);
         }
      };
      document.addEventListener('mousedown', handleClickOutside);
      return () => {
         document.removeEventListener('mousedown', handleClickOutside);
      };
   }, [connectingStart]);

   const completeConnection = useCallback(
      (toCardId: string, toSide: ConnectionSide) => {
         if (connectingStart && connectingSide && connectingStart !== toCardId) {
            const newConnection: Omit<Connection, 'id'> = {
               from: connectingStart,
               to: toCardId,
               fromSide: connectingSide,
               toSide: toSide,
               tabId
            };
            createConnection(newConnection).then(() => {
               refresh()
            })
         }
         setConnectingStart(null);
         setConnectingSide(null);
      },
      [connectingStart, connectingSide, connections]
   );

   const deleteConnection = (id: string) => {
      delConn(id).then(() => {
         refresh()
      })
   }

   const hasConnectionOnSide = useCallback(
      (cardId: string, side: ConnectionSide) => {
         return connections.some(
            (conn) => (conn.from === cardId && conn.fromSide === side) || (conn.to === cardId && conn.toSide === side)
         );
      },
      [connections]
   );

   const getConnectionHandlers = (cardId: string, hoveredCardId: string | null) =>
      HandlerList.map((handler) => {
         const side = handler.position as ConnectionSide;
         const hasConnection = hasConnectionOnSide(cardId, side);
         const isInConnectingMode = connectingStart !== null;

         const showMinus = !isInConnectingMode && hasConnection && hoveredCardId === cardId;

         const fromSide = connectingSide === side && connectingStart === cardId
         const otherCard = connectingStart !== cardId

         return (
            <div
               key={handler.position}
               className={`connection-handle ${handler.position}`}
               style={{
                  ...HandlerCommonStyle,
                  ...handler.style,
                  backgroundColor: connectingStart === cardId ? '#4299e1' : showMinus ? '#e53e3e' : '#a0aec0',
                  display: (!connectingStart && hoveredCardId === cardId) || (connectingStart && (fromSide || otherCard)) ? 'flex' : 'none',

               }}
               onClick={(e) => {
                  e.stopPropagation();

                  if (showMinus) {
                     const ids = connections.filter((conn) => (conn.from === cardId && conn.fromSide === side) || (conn.to === cardId && conn.toSide === side)).map((conn) => conn.id)
                     delconns(ids).then(() => {
                        refresh()
                     })
                  } else if (connectingStart) {
                     completeConnection(cardId, side);
                  } else {
                     startConnection(cardId, side);
                  }
               }}
            >
               {/* 根据状态显示加号或减号 */}
               {showMinus ? '−' : '+'}
            </div>
         );
      });

   return {
      connections,
      connectingStart,
      setConnections,
      startConnection,
      completeConnection,
      deleteConnection,
      hasConnectionOnSide,
      getConnectionHandlers
   };
};

export default useConnections;
